<template>
  <div>
    <canvas width="200" height="40" id="myCanvas" @click="myGetVeri"> </canvas>
  </div>
</template>
<script>
import { getVeri } from '../../api/common'
export default {
  data () {
    return {
      veri: ''
    }
  },
  created () {},
  beforeMount () {},
  mounted () {
    this.myGetVeri()
  },
  methods: {
    async myGetVeri () {
      //获取验证码接口
      var res = await getVeri()
      console.log(res)
      this.veri = res.data.data
      this.init(this.veri) //绘制验证码
    },
    init (str) {
      var myCanvas = document.getElementById('myCanvas')
      var ctx = myCanvas.getContext('2d')
      ctx.clearRect(0, 0, 200, 40)
      console.log(ctx)
      for (var i = 0; i < str.length; i++) {
        ctx.font = '30px 黑体'
        ctx.fillStyle = this.ranColor()
        ctx.fillText(str[i], i * 50 + this.ranDom(5, 10), this.ranDom(20, 40))
      }
      // 10个干扰线
      for (var j = 0; j < 5; j++) {
        ctx.beginPath()
        ctx.moveTo(this.ranDom(0, 200), this.ranDom(0, 40))
        ctx.lineTo(this.ranDom(0, 200), this.ranDom(0, 40))
        ctx.strokeStyle = this.ranColor() //随机线的颜色
        ctx.stroke()
      }
      // 20干扰点
      for (var k = 0; k < 20; k++) {
        ctx.beginPath()
        var x = this.ranDom(0, 200)
        var y = this.ranDom(0, 40)
        ctx.moveTo(x, y)
        ctx.lineTo(x + 2, y + 2)
        ctx.strokeStyle = this.ranColor() //随机线的颜色
        ctx.stroke()
      }
    },
    ranDom (a, b) {
      //随机函数
      return Math.floor(Math.random() * (b - a) + a)
    },
    ranColor () {
      //随机颜色
      return `rgb(${this.ranDom(0, 255)},${this.ranDom(0, 255)},${this.ranDom(
        0,
        255
      )})`
    }
  }
}
</script>
<style lang="less">
#myCanvas {
  background: skyblue;
}
</style>
